<?php

namespace app\validator;

use app\models\AdminSupplier as Model;
use yii\validators\Validator;

class AdminSupplierValidator extends Validator
{
    // 用户名是否存在
    public function validateAttribute($model, $attribute)
    {
        $query = Model::find()
            ->where(['username' => $model->username]);

        // 修改时
        if ($model['id']) {
            $query->andWhere(['!=', 'id', $model->id]);
        }

        // p_id
        $query->andWhere(['p_id' => $model->p_id]);

        $has = $query->one();

        if ($has) {
            $this->addError($model, $attribute, '用户名:' . $model->username . '已经存在');
        }
    }
}